<?php

namespace App\Models;

use Carbon\Carbon;
use DB;
use Illuminate\Database\Eloquent\Model;

class Credit extends Model
{
    public $timestamps = false;
    protected $guarded = [];

    public static function integrityAnalysis($type='month',$module='guides',$limit=6){
        $x = [];
        $arg = [
            'month'=>'m',
            'year'=>'Y',
            'day'=>'d'
        ];
        for ($i=$limit-1;$i>=0;$i--){
            array_push($x,date($arg[$type],strtotime("-".$i." ".$type)));
        }
        $list = self::select([$type,DB::raw('Count('.$type.') as count')])
            ->where('module',$module)
            ->groupBy($type)->get();
        $score=[];
        if(count($list)>0){
            foreach ($x as $key=>$val){
                foreach ($list as $v){
                    if($v[$type]==$val){
                        $score[$key]=100-(int)$v->count;
                        break;
                    }else
                        $score[$key]=100;
                }
            }
        }else{
            for ($i=$limit-1;$i>=0;$i--){
                array_push($score,100);
            }
        }
        return ['x'=>$x,'y'=>$score];
    }

    public static function getAllAnalysis($year=null){
        $x = collect(config('options.credit_module'))->values();
        $year=$year==null?Carbon::now()->startOfYear()->toDateString():$year;
        $list = self::select(['module',DB::raw('Count(module) as count')])
                ->where('year',2016)
                ->groupBy('module')
                ->get();
        $score=[];
        if(count($list)>0){
            foreach ($x as $key=>$val){
                foreach ($list as $v){
                    $k = config('options.credit_module')[$v->module];
                    if($val==$k){
                        $score[$key]=100-(int)$v->count;
                        break;
                    }else
                        $score[$key]=100;
                }
            }

        }else{
            foreach ($x as $v){
                array_push($score,100);
            }
        }
        return [
            'x'=>$x,
            'y'=>$score
        ];
    }
}